package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //菜品列表分页查询
    @GetMapping("/dish/page")
    public ResultInfo findByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            String name
    ) {
        //1. 调用service分页查询
        Page<Dish> page = dishService.findByPage(name, pageNum, pageSize);

        //2. 返回结果
        return ResultInfo.success(page);
    }
    @PostMapping("/dish")
    public ResultInfo save (@RequestBody Dish dish){

        //设置一个key
        Set keys = redisTemplate.keys("dish_*");

        //删除菜品
        redisTemplate.delete(keys);
        dishService.save(dish);
        return  ResultInfo.success(null);
    }
    @GetMapping("/dish/{id}")
    public ResultInfo findById(@PathVariable("id")Long id ){
        Dish dish = dishService.findById(id);
        return ResultInfo.success(dish);

    }
    //修改，更新
    @PutMapping("/dish")
    public ResultInfo update(@RequestBody Dish dish){
        //创建一个key
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.save(dish);
        return ResultInfo.success(null);

    }
    //起售，停售
    @PostMapping("/dish/status/{status}")
    public ResultInfo deleteByIds(@PathVariable("status") Integer status, Long[] ids){
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        if (ids!= null && ids.length>0){
            dishService.updateByIds(ids,status);
        }
        return  ResultInfo.success(null);
    }

    //删除
    @DeleteMapping("/dish")
    public ResultInfo deleteByIds(Long [] ids){
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);


        if (ids != null && ids.length >0){
            dishService.deleteByIds(ids);


        }
        return  ResultInfo.success(null);
    }
    @GetMapping("/dish/list")
    public ResultInfo findByCategoryId(Long categoryId){
        List<Dish>dishList = dishService.findByCategoryId(categoryId);
        return ResultInfo.success(dishList);
    }
}